import {CheckCircleTwoTone, ExportOutlined} from '@ant-design/icons';
import {Button, message, Popconfirm, Tag, List} from 'antd';
import React, {useState, useRef} from 'react';
import {FooterToolbar} from '@ant-design/pro-layout';
import type {ProColumns, ActionType} from '@ant-design/pro-table';
import ProTable from '@ant-design/pro-table';

import {removeData, dataList, download, loadData, updateData} from './service';
import type {QuestionBody, QuestionListItem, QuestionListPagination} from './data';
import ProForm, {
  ModalForm, ProFormDigit,
  ProFormInstance, ProFormList, ProFormText
} from "@ant-design/pro-form";

/**
 * 删除节点
 *
 * @param selectedRows
 */
const handleRemove = async (selectedRows: QuestionListItem[], isPlan: boolean) => {
  const hide = message.loading('正在删除');
  if (!selectedRows) return true;

  try {
    await removeData(selectedRows.map((row) => row.questionId), isPlan);
    hide();
    message.success('删除成功，即将刷新');
    return true;
  } catch (error) {
    hide();
    message.error('删除失败，请重试');
    return false;
  }
};

type QuestionProps = {
  type?: number;
  keys?: React.Key[];
  selectMode?: boolean;
  onSelectData?: (keys: React.Key[], dataList: QuestionListItem[]) => void;
};
const QuestionList: React.FC<QuestionProps> = (props) => {
  const {type, keys, selectMode, onSelectData} = props;
  // const [createModalVisible, handleModalVisible] = useState<boolean>(false);
  // const [questionModalVisible, handleQuestionModalVisible] = useState<boolean>(false);
  // const [questionModalTitle, handleQuestionModalTitle] = useState<string>("试题管理");
  // const [showDetail, setShowDetail] = useState<boolean>(false);
  const actionRef = useRef<ActionType>();
  const formRef = useRef<ProFormInstance>();
  const [currentRow, setCurrentRow] = useState<QuestionListItem>();
  const [selectedRowsState, setSelectedRows] = useState<QuestionListItem[]>([]);
  const [dataLoading, setDataLoading] = useState<boolean>(true);
  const [createModalVisible, handleModalVisible] = useState<boolean>(false);

  const columns: ProColumns<QuestionListItem>[] = [
    {
      title: '序号',
      dataIndex: 'index',
      width: 58,
      align: 'center',
      hideInTable: selectMode,
      valueType: 'indexBorder',
      render: (dom, entity, index) => {
        return (
          <span>
            {index +
              1 +
              ((actionRef?.current?.pageInfo?.current || 1) - 1) *
              (actionRef?.current?.pageInfo?.pageSize || 5)}
          </span>
        );
      },
    },
    {
      title: '题干',
      dataIndex: 'title',
      width: 300,
    },
    {
      title: '选项',
      dataIndex: 'options',
      hideInSearch: true,
      width: 300,
      render: (_, record) => (
        <List
          size="small"
          bordered
          dataSource={record.options}
          renderItem={(item) => (
            <List.Item>
              {item.text}
              {item.answer ? <CheckCircleTwoTone twoToneColor="#52c41a"/> : <></>}
            </List.Item>
          )}
        />
      ),
    },
    {
      title: '所属计划',
      dataIndex: 'name',
      hideInSearch: true,
      width: 300,
      hideInTable: selectMode,
    },
    {
      title: '所属课件',
      hideInSearch: true,
      dataIndex: 'name',
      hideInTable: !selectMode,
    },
    {
      title: '课件标签',
      hideInSearch: true,
      dataIndex: 'tags',
      hideInTable: !selectMode,
      render: (_, record) => (
        <>
          {record?.coursewareTags?.map((name, index) => (
            <Tag key={name + index + record.questionId}>{name}</Tag>
          ))}
        </>
      ),
    },
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      hideInDescriptions: true,
      render: (_, record) => {
        if (record.enterpriseId > 0) {
          return [

            <a
              key="edit"
              onClick={() => {
                formRef.current?.resetFields();
                console.log(record);
                setCurrentRow(record);
                handleModalVisible(true);
              }}
            >
              编辑
            </a>,
            <Popconfirm
              key="delete"
              okButtonProps={{danger: true}}
              title={`确认删除课件：${record.name}?`}
              onConfirm={async () => {
                setCurrentRow(record);
                await handleRemove([record], !selectMode);
                actionRef.current?.reloadAndRest?.();
              }}
              okText="删除"
              cancelText="取消"
            >
              <a href="#"> 删除 </a>
            </Popconfirm>
          ]
        }
        return [];
      },
    },
  ];

  return (
    <>
      <ProTable<QuestionListItem, QuestionListPagination>
        headerTitle={'课件列表'}
        actionRef={actionRef}
        formRef={formRef}
        rowKey="questionId"
        // manualRequest={true}
        pagination={{pageSize: selectMode ? 10 : 20}}
        // scroll={{x: 1200}}
        search={
          {
            // labelWidth: 120,
          }
        }
        onLoadingChange={(loading) => {
          setDataLoading(loading as boolean);
        }}
        form={{ignoreRules: false}}
        options={false}
        // @ts-ignore
        toolBarRender={() => {
          return [
            <Button
              type="primary"
              key="primary"
              loading={dataLoading}
              onClick={async () => {
                let fieldFormatValueObject = formRef.current?.getFieldFormatValueObject?.();
                await download({...fieldFormatValueObject, selectMode});
              }}
            >
              <ExportOutlined/> 导出
            </Button>,
          ]

        }}
        request={dataList}
        columns={columns}
        // @ts-ignore
        params={{type, selectMode}}
        rowSelection={{
          type: type == 2 ? 'radio' : 'checkbox',
          selectedRowKeys: keys,
          preserveSelectedRowKeys: true,
          onChange: (_, selectedRows) => {
            setSelectedRows(selectedRows);
            onSelectData && onSelectData(_, selectedRows);
          },
        }}
      />
      {selectedRowsState?.length > 0 && !selectMode && (
        <FooterToolbar
          extra={
            <div>
              已选择{' '}
              <a
                style={{
                  fontWeight: 600,
                }}
              >
                {selectedRowsState.length}
              </a>{' '}
              个课件
            </div>
          }
        >
          <Popconfirm
            key="delete"
            title={`确认删除选中的${selectedRowsState.length}个课件?`}
            okButtonProps={{danger: true}}
            onConfirm={async () => {
              await handleRemove(selectedRowsState, !selectMode);
              setSelectedRows([]);
              actionRef.current?.reloadAndRest?.();
            }}
            okText="删除"
            cancelText="取消"
          >
            <Button danger>批量删除</Button>
          </Popconfirm>
          {/*<Button type="primary">批量审批</Button>*/}
        </FooterToolbar>
      )}

      <ModalForm<QuestionBody>
        title={'编辑问题'}
        formRef={formRef}
        layout={'horizontal'}
        labelCol={{span: 4}}
        wrapperCol={{span: 16}}
        visible={createModalVisible}
        onVisibleChange={(visible) => {
          if (!visible) {
            setCurrentRow(undefined);
          }
          handleModalVisible(visible);
        }}
        modalProps={{destroyOnClose: true, maskClosable: false}}
        onFinish={async (value) => {
          console.log(value);
          const hide = message.loading('正在保存');
          // if (editMode) {
          try {
            await updateData({...value}, !selectMode);
            hide();
            message.success('保存成功');
            handleModalVisible(false);
            // @ts-ignore
            actionRef?.current?.reloadAndRest();
          } catch (error) {
          }
        }}
        // @ts-ignore
        request={(params: QuestionBody) => {
          console.log(params);
          if (params.questionId > 0) {
            return loadData(params, !(selectMode ?? false)).then(({data}) => {
              console.log(data)
              return data;
            });
          }
        }}
        params={{...currentRow}}
      >
        <ProFormText hidden name="questionId"/>
        <ProFormText rules={[{required: true}]} label={'课件名称'} name="title"/>
        <ProFormDigit rules={[{required: true}]}
                      extra={<div style={{color: "#e67c26", marginTop: 5}}>注意:答案填写的是下面选项的编号</div>}
                      label={'正确答案'} name="answer"/>
        <ProForm.Item required isListField style={{marginBlockEnd: 0}} label="选项">
          <ProFormList
            name="options"
            // creatorButtonProps={false}
            min={1}
            max={4}
            itemRender={({listDom, action}, {index}) => (
              <>
                <ProFormText hidden name={['key']}/>
                <ProFormText
                  rules={[{
                    required: true,
                    message: <div>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;选项{(index + 1).toString()}不能为空</div>
                  }]}
                  width={"lg"}
                  allowClear={false}
                  name={['text']}
                  addonBefore={(index + 1).toString() + '.'}/>
              </>
              // <Row>
              //   <Col flex="20px" style={{textAlign: "center"}}> </Col>
              //   <Col flex="auto">{listDom}</Col>
              // </Row>
            )}
            deleteIconProps={false}
            copyIconProps={false}
          >
          </ProFormList>
        </ProForm.Item>
      </ModalForm>
    </>
  );
};

export default QuestionList;
